#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mg_iic.h"
#include "iic/mmp_iic.h"
#include "mg_Rs485Protocol.h"
/*****************I2C0**************/
//初始化IIC0
void I2C0_Init(void)
{
#ifdef CFG_I2C0_ENABLE
	mmpIicInitialize(IIC_PORT_0, IIC_MASTER_MODE, 0, 0, 400 * 1000, 0);
#endif
}
//I2C0读8位寄存器字节
uint8_t I2C0_Read_8Reg(uint8_t SlaveAddr, uint8_t regAddr)
{
	uint8_t RecieveBuf;
	bool result = false;
	result = mmpIicReceiveData(IIC_PORT_0, IIC_MASTER_MODE, SlaveAddr, &regAddr, 1, &RecieveBuf, 1);
	return RecieveBuf;
}
//I2C0读16位寄存器字节
uint8_t I2C0_Read_16Reg(uint8_t SlaveAddr, uint8_t regHAddr, uint8_t regLAddr)
{
	uint8_t count = 200;
	uint8_t RecieveBuf;
	uint8_t RegAddr[2];
	RegAddr[0] = regHAddr;
	RegAddr[1] = regLAddr;
	bool result = false;
	while (count--)
	{
		result = mmpIicReceiveData(IIC_PORT_0, IIC_MASTER_MODE, SlaveAddr, RegAddr, 2, &RecieveBuf, 1);
		if (result)break;
	}
	if (count == 0)//写入错误
	{
		RS485_Tx_SaveErr(2);
	}
	return RecieveBuf;
}
//I2C0读16位寄存器字节
void I2C0_Read_More_16Reg(uint8_t SlaveAddr, uint8_t regHAddr, uint8_t regLAddr,uint8_t* Data, uint32_t DataLen)
{
	uint8_t RegAddr[2];
	RegAddr[0] = regHAddr;
	RegAddr[1] = regLAddr;
	bool result = false;
	result = mmpIicReceiveData(IIC_PORT_0, IIC_MASTER_MODE, SlaveAddr, RegAddr, 2, Data, DataLen);
}
//I2C0写8位寄存器
uint32_t I2C0_Write_8Reg(uint8_t SlaveAddr, uint8_t RegAddr, uint8_t* Data, uint8_t DataLen)
{
	return mmpIicSendData(IIC_PORT_0, IIC_MASTER_MODE, SlaveAddr, RegAddr, Data, DataLen);
}
//I2C0写16位寄存器(最大256长度)
void I2C0_Write_16Reg(uint8_t SlaveAddr, uint8_t RegHAddr, uint8_t RegLAddr,uint8_t* Data, uint16_t DataLen)
{
	uint8_t TempData[257];
	TempData[0] = RegLAddr;
	memcpy(&TempData[1], Data, DataLen);
	mmpIicSendData(IIC_PORT_0, IIC_MASTER_MODE, SlaveAddr, RegHAddr, TempData, DataLen + 1);
}
/*****************I2C2**************/
//初始化IIC2
void I2C2_Init(void)
{
#ifdef CFG_I2C2_ENABLE
	mmpIicInitialize(IIC_PORT_2, IIC_MASTER_MODE, 0, 0, 100 * 1000, 0);
#endif
}
//I2C2读寄存器字节
uint8_t I2C2_Read_Reg(uint8_t SlaveAddr, uint8_t regAddr)
{
	uint8_t RecieveBuf;
	bool result = false;
	result = mmpIicReceiveData(IIC_PORT_2, IIC_MASTER_MODE, SlaveAddr, &regAddr, 1, &RecieveBuf, 1);
	return RecieveBuf;
}
//I2C2写寄存器
void I2C2_Write_Reg(uint8_t SlaveAddr, uint8_t RegAddr,uint8_t* Data, uint8_t DataLen)
{
	mmpIicSendData(IIC_PORT_2, IIC_MASTER_MODE, SlaveAddr, RegAddr, Data, DataLen);
}

void Mg_I2C_Init(void)
{
#ifndef _WIN32
	I2C0_Init();
	I2C2_Init();
#endif
}